package com.itheima.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.itheima.common.CommonResult;
import com.itheima.common.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。private

    //调用阿里云oss上传文件

    @Autowired
    private OssProperties ossProperties;

    @PostMapping("/upload")
    public CommonResult upload(MultipartFile file) {
        log.info("文件名：{}", file.getOriginalFilename());


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getAccesskey(), ossProperties.getSecret());

        try {
            ossClient.putObject(ossProperties.getBucketName(), file.getOriginalFilename(), file.getInputStream());
        } catch (Exception oe) {
            log.error("上传出现异常");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String fileUrl = ossProperties.getUrl() + "/" + file.getOriginalFilename();
        return CommonResult.success("上传成功", fileUrl);
    }
}
